﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace PlanetenGravity
{
    public class Gravity<T>
    {
        public Gravity(T t1, T t2)
        {
            PlanetaryForce(t1 as Planet, t2 as Sprite);
        }

        private void PlanetaryForce(Planet p, Sprite s)
        {
            Vector2 distance = s.Position - p.Position;

            // If s is outside the gravity field of p, 
            // then do not apply any gravity to it
            if (distance.Length() - s.Radius > p.Radius + p.GravityField)
                return;

            float total = (float)Math.Sqrt(distance.X * distance.X +
                                           distance.Y * distance.Y);

            float force =
                (p.GravityStrength * (100 - s.Mass) * p.Mass) / (total * total);

            float x = (Math.Abs(distance.X) / total) * force;
            float y = (Math.Abs(distance.Y) / total) * force;

            if (p.Position.X >= s.Position.X)
                s.Position.X += x;
            else
                s.Position.X -= x;

            if (p.Position.Y >= s.Position.Y)
                s.Position.Y += y;
            else
                s.Position.Y -= y;
        }
    }
}
